<template>
  <div class="container mult-upload-container">
    <div class="mult-upload-file-box" @click="multUploadListVisible=true">      
      <div
        v-bind="$attrs"
        v-on="$listeners"
        :disabled="disabled"
        class="mult-image-uploader">
        <i class="iconfont df-iconweb-icon- image-uploader-icon"></i>
      </div>
      <img v-if="imageUrl && urlType == 'image'" :src="imageUrl" class="image-viewer" title="点击图片上传">
      <span v-if="imageUrl && urlType != 'image'" class="image-viewer" :class="urlType+'-view'" title="点击图片上传"></span>
      <div class="mult-image-toolbar">
        <div class="mult-image-toolbar-box num">
          {{ uploadFileList.length }}
        </div>
      </div>
    </div>
    <div class="upload-title-box" :title="label || item.lable">
      <el-tooltip class="item" effect="dark" content="必填" placement="top">
        <i class="el-icon-star-on" v-if="required === 1 || item.required" style="color: #F56C6C;"></i>
      </el-tooltip>
      <label for="" :title="label || item.label">{{label || item.label}}</label>
    </div>
    <el-dialog 
      class="mult-dialog-form"
      :title="item.tag_limits == 0?label  + '【不限制个数】' || item.label + '【不限制个数】':label  + '【最大限制 ' + item.tag_limits + ' 个】' || item.label + '【最大限制 ' + item.tag_limits + ' 个】'"
      width="60%"
      :destroy-on-close="true"
      :close-on-click-modal="false"
      :visible.sync="multUploadListVisible"
      append-to-body>
      <div class="mult-el-dialog-body-div" style="height: 550px;">
        <viewer :images="uploadFileUrlList" ref="uploadViewer">
           <img
              :ref="'uploadViewer' + index"
              v-for="(src,index) in uploadFileUrlList"
              :src="src"
              :key="index"
              style="display:none"
            >
        </viewer>      
        <avue-crud
          :data="uploadFileList"
          :option="tableOption">
          <template slot="src" slot-scope="scope" >
            <img v-if="scope.row.type == 'image'" class="columnImg" 
              :src="scope.row.src" @click="imgEnlarge(scope)" title="点击图片预览"/>
            <a v-if="scope.row.type != 'image'" :href="scope.row.src" class="otherColumnImg" :class="scope.row.type+'-view'" title="点击图片下载" download></a>
          </template>
          <template slot="progress" slot-scope="scope" >
            <el-progress :percentage="scope.row.progress"></el-progress>
          </template>
          <!-- :multiple="item.tag_limits === 1 ? false : true" -->
          <template slot="menuLeft">
            <el-row>
              <el-upload
                class="inline-block"
                ref="multUploadEl"
                :headers="headers"
                :action="uploadFilesUrl"       
                :multiple="item.tag_limits === 1?false:true"       
                v-bind="$attrs"
                v-on="$listeners"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
                :on-progress="handleProgress"
                :on-success="successUpload"
                :on-error="errorUpload">    
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
              <!-- <el-button style="margin-left: 10px;" size="small" type="success" @click="saveUpload">保存文件</el-button>               -->
            </el-row>
          </template>
          <template slot="menu" slot-scope="{row}">
            <el-button 
              size="small"
              type="text"
              @click.native="handleDel(row)">
              删除
            </el-button>
          </template>
        </avue-crud>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { objectStore } from '@/api/common'
import { matchType } from '@/util/upload';

export default {
  props: {
    item: {
      type: Object,
      required: true
    },
    disabled: Boolean,
    value: Array,
    label: String,
    required: Number,
    prop: String
  },
  data() {
    return {
      multUploadListVisible: false,
      multUploadListTitle: '',
      uploadFileList: [],
      // uploadFileUrlList: [],
      headers:{
        uid:this.$store.getters.userInfo.id,
        token:this.$store.getters.token
      },
      page: {
        pageSizes: [10],
        currentPage: 1,
        total: 0,
        pageSize: 10
      }, // 分页信息
      tableOption: {
        border: true,
        size: 'mini',
        page: false,
        align: 'left',
        menuAlign: 'center',
        addBtn: false,
        delBtn: false,
        editBtn: false,
        menu: true,
        maxHeight: 500,
        column:[{ // 表格列
          prop: 'name',
          label: '文件名'
        },{
          prop: 'src',
          label: '图片',
          slot: true
        },{
          prop: 'code',
          label: '状态'
        },{
          prop: 'progress',
          label: '进度',
          slot: true
        }]
      }
    };
  },
  watch: {
    value: {
      deep: true, // 深度监听
      immediate:true,
      handler(val) {
        for (var i = 0; i < val.length; i++) {
          this.$set(val[i], 'type', matchType(val[i].key))
        }
        this.uploadFileList = val
        console.log('multUploadListvalue',val)
      }
    }
  },
  computed: {
    imageUrl () {
      let _url = ''
      if(this.uploadFileList.length > 0) {
        _url = this.uploadFileList[0].src
      }
      return _url
    },
    urlType () {
      let _type = ''
      if(this.uploadFileList.length > 0) {
        _type = this.uploadFileList[0].type
      }
      return _type
    },
    uploadFileUrlList () {
      let _arr = []
      this.uploadFileList.forEach((element) => {
        if (element.hasOwnProperty('src') && element.src != "" && element.hasOwnProperty('type') && element.type == 'image') {
          _arr.push(element.src)
        }
      })
      console.log('uploadFileUrlList',_arr)
      return _arr
    },
    uploadFilesUrl () {
      let _this = this,
        _url = ''

      if (_this.item.hasOwnProperty('uploadUrl') && _this.item['uploadUrl'] !== '') {
        _url = objectStore[_this.item.uploadUrl]
      } else {
        if (_this.item.hasOwnProperty('fileType') && _this.item['fileType'].length === 1 && _this.item['fileType'][0] === 'image') {
          _url = objectStore['upload_img']
        } else {
          _url = objectStore['upload_file']
        }
      }

      return _url
    }
  },
  methods: {
    // 图片放大
    imgEnlarge (scope) {     
      this.$refs['uploadViewer' + scope.row.$index][0].click()
    },
    // 重新上传
    handleUpdate () {
      this.$refs.uploadEl.$refs['upload-inner'].$refs.input.click()
    },
    // 保存文件
    saveUpload() {
      let _this = this
      _this.uploadFileList.forEach((element, index) => {
        element.progress = 100
        element.code = '已保存'
        _this.$set(_this.uploadFileList, index, element);
      })
      _this.$emit('handleSave', { item: _this.item, key: _this.item.prop, fileList: _this.uploadFileList})  
    },
    // 更新进度条
    handleProgress(event, file) {
      this.uploadFileList.forEach((element, index) => {
        if (element.uid === file.uid) {
          // 更新这个uid下的进度
          const progress = Math.floor(event.percent)
          // 防止上传完接口还没有返回成功值，所以此处给定progress的最大值为99，成功的钩子中再置为100
          element.progress = progress === 100 ? 99 : progress
          this.$set(this.uploadFileList, index, element);
          this.$emit('uploadChange', { item: this.item, key: this.item.prop, fileList: this.uploadFileList})
        }
      })
    },
    //上传之前操作
    beforeAvatarUpload(file) {
      console.log(file);

      if (parseInt(this.item.tag_limits) != 0) {
        if (this.uploadFileList.length + 1 > parseInt(this.item.tag_limits)) {
          this.$message.error('最多允许上传' + this.item.tag_limits + '个文件')
          return false
        }
      }


      //判断上传文件大小
      if(this.item.size && this.item.size != '' && this.item.size != 0){
        const isLt2M = file.size / 1024 < Number(this.item.size);
        let isMinSize = true
        if (this.item.hasOwnProperty('minsize')) {
          isMinSize = file.size / 1024 > Number(this.item.minsize);
        }
        if (!isLt2M || !isMinSize) {
          let numStr = this.item.size + 'KB'
          if(Number(this.item.size) / 1024  > 0){
            numStr = Math.round((Number(this.item.size) / 1024) * 100) / 100 + 'MB'
          }
          if (this.item.hasOwnProperty('sizeError')) {
            this.$message.error(this.item.sizeError);
          } else if(this.item.hasOwnProperty('minsize')) {
            let minnumStr = this.item.minsize + 'KB'
            if(Number(this.item.minsize) / 1024  > 0){
              minnumStr = Math.round((Number(this.item.minsize) / 1024) * 100) / 100 + 'MB'
            }
            this.$message.error('上传文件大小不能小于 '+ minnumStr +',不能超过 ' + numStr + '!');
          } else {
            this.$message.error('上传文件大小不能超过 ' + numStr + '!');
          }
          this.uploadLoading = false
          return false
        }
      }
      //判断上传文件类型
      if(this.item.fileType.length > 0){
        let matchFileType = matchType(file.name)
        const isFileType = matchFileType.indexOf(this.item.fileType.join(',')) != -1
        if (!isFileType) {
          this.$message.error('上传文件格式不正确!');
          this.uploadLoading = false
          return isFileType
        }
      }
      if (this.item.hasOwnProperty('fileTypeSuffix') && this.item.fileTypeSuffix.length > 0) {
        let suffix = ''
        try {
          var flieArr = file.name.split('.');
          suffix = flieArr[flieArr.length - 1];
        } catch (err) {
          suffix = '';
        }
        const isFileTypeSuffix = suffix.indexOf(this.item.fileTypeSuffix.join(',')) != -1
        if (!isFileTypeSuffix) {
          this.$message.error('上传文件格式不正确,为 '+this.item.fileTypeSuffix.join(',')+' 格式!');
          this.uploadLoading = false
          return isFileTypeSuffix
        }
      }
      
      // 大小和类型验证都通过后，给自定义的列表中添加需要的数据
      this.objAddItem(file)
    },
    successUpload(response, file) {
      console.log(response)
      let _this = this
      if(response.code === 10000){
        _this.uploadFileList.forEach((element, index) => {
          if (element.uid === file.uid) {
            element.progress = 100
            element.code = '已上传'
            this.$set(element, 'type', matchType(response.data.key))
            element.src = response.data.src
            element.key = response.data.key
            _this.$message.success(response.message);
            _this.$set(_this.uploadFileList, index, element);
            _this.$emit('uploadChange', { item: _this.item, key: _this.item.prop, fileList: _this.uploadFileList})
          }
        })         
      }else{
        _this.uploadFileList.forEach((element, index) => {
          if (element.uid === file.uid) {
            _this.uploadFileList.splice(index, 1); // 上传失败删除该记录
            _this.$message.error(response.message);
            _this.$emit('uploadChange', { item: _this.item, key: _this.item.prop, fileList: _this.uploadFileList})
          }
        })
      }
    },
    errorUpload(err, file) {     
      let _this = this
      _this.uploadFileList.forEach((element, index) => {
        if (element.uid === file.uid) {
          _this.uploadFileList.splice(index, 1); // 上传失败删除该记录
          _this.$message.error(err);
          _this.$emit('uploadChange', { item: _this.item, key: _this.item.prop, fileList: _this.uploadFileList})
        }
      })     
    },
    handleDel (row) {
      let _this = this
      _this.$confirm('确定删除' + row.name + '附件？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {        
        _this.uploadFileList.forEach((element, index) => {
          if (row.hasOwnProperty('id') && element.id === row.id) {
            _this.uploadFileList.splice(index, 1);
            _this.$emit('uploadDel', { item: _this.item, key: _this.item.prop, id: row.id, fileList: _this.uploadFileList})
          } else if(row.hasOwnProperty('uid') && element.uid === row.uid) {
            _this.uploadFileList.splice(index, 1);            
            _this.$emit('uploadChange', { item: _this.item, key: _this.item.prop, fileList: _this.uploadFileList})
          }
        })          
      }).catch(()=>{})
    },
    // 添加数据函数
    objAddItem (file) {
      let _param = {
        uid: file.uid, // uid用于辨别文件
        name: file.name, // 列表显示的文件名
        src: '',
        progress: 0, // 进度条
        code: '已添加', // 上传状态
        key: '',
        type: matchType(file.name)
      }
      this.uploadFileList.push(_param)
      this.$emit('uploadChange', { item: this.item, key: this.item.prop, fileList: this.uploadFileList}) 
    }
  }
}
</script>

<style scoped="scoped" lang="scss">
  .columnImg{
    max-width: 100px;
    max-height: 30px;
  }
  .otherColumnImg {
    display: block;
    width: 30px;
    height: 30px;
  }
  .mult-upload-container{
    height: 200px;
    width: 240px;    
    .mult-upload-file-box {
      position: relative;
      margin: 0 auto;
      width: 95%;
      height: 160px;
      background: rgba(240,240,240,1);
      cursor: pointer;
      .mult-image-uploader {
        position: absolute;
        top: 0;
        left: 0;
        z-index: 1;
        width: 100%;
        text-align: center;
        .image-uploader-icon {
          font-size: 43px;
          color: #8c939d;
          width: 100%;
          height: 160px;
          line-height: 160px;
          text-align: center;
        }
      }
      .image-viewer {
        position: absolute;
        top: 0;
        left: 0;
        z-index: 2;
        width: 100%;
        height: 160px;
        display: block;
        cursor: pointer;
      }
      .no-image-viewer {
        display: block;
        position: absolute;
        top: 0;
        left: 0;
        z-index: 2;
        width: 100%;
        height: 160px;
        line-height: 160px;
        text-align: center;
        background: #f0f0f0;
      }
      .mult-image-toolbar {
        position: absolute;
        top: 0;
        right: 0;
        z-index: 3;
        height: 40px;
        line-height: 40px;
        // background: rgba(255, 255, 255, .2);
        .mult-image-toolbar-box {
          float: right;
          min-width: 32px;
          height: 32px;
          line-height: 32px;
          text-align: center;
          border-radius:2px;
          font-size: 16px;
        }
        .mult-image-toolbar-box.num {
          background: #4285F4;
          color: #fff;
        }
      }
    }
    .upload-title-box {
      margin: 0 auto;
      width: calc(95% - 2px);
      height: 39px;
      line-height: 39px;
      border:1px solid rgba(221,221,221,1);
      border-top: none;
      text-align: center;
      text-overflow:ellipsis; 
      overflow:hidden;
      white-space:nowrap;
    }
    .slide-fade-enter-active {
      transition: all .3s ease;
    }
    .slide-fade-leave-active {
      transition: all .8s cubic-bezier(1.0, 0.5, 0.8, 1.0);
    }
    .slide-fade-enter, .slide-fade-leave-to
    /* .slide-fade-leave-active for below version 2.1.8 */ {
      transform: translateY(-40px);
      opacity: 0;
    }
  }
</style>
